package com.smt.take.ui.activity

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.amap.api.maps2d.AMap
import com.amap.api.maps2d.AMapUtils
import com.amap.api.maps2d.CameraUpdateFactory
import com.amap.api.maps2d.model.*
import com.smt.take.R
import com.smt.take.utils.OrderObservable
import kotlinx.android.synthetic.main.activity_order_detail.*
import org.json.JSONObject
import java.util.*
import kotlin.collections.ArrayList
import kotlin.math.abs


class OrderDetailActivity : BaseActivity(), Observer {

    //初始化地图控制器对象
    lateinit var aMap: AMap
    private lateinit var riderMarker: Marker
    private val points: ArrayList<LatLng> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_order_detail)
        // 判断设备是否有虚拟按键
        if (checkDeviceHasNavigationBar(this)) {
            llOrderDetail.setPadding(0, 0, 0, 48.dp2px())
        }
        OrderObservable.instance.addObserver(this)
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState)
        //初始化地图控制器对象
        aMap = mMapView.map
        processIntent()
    }

    lateinit var orderId: String
    lateinit var type: String

    private fun processIntent() {
        if (intent.hasExtra("orderId")) {
            orderId = intent.getStringExtra("orderId").toString()
            type = intent.getStringExtra("type").toString()
            setState()
        }
    }

    private fun setState() {
        val index = getIndex(type)
        (ll_order_detail_type_point_container.getChildAt(index) as ImageView).setImageResource(R.drawable.order_time_node_disabled)
        (ll_order_detail_type_container.getChildAt(index) as TextView).setTextColor(Color.BLUE)
    }

    private fun getIndex(type: String): Int {
        var index = -1
        // String typeInfo = "";
        when (type) {
            OrderObservable.ORDERTYPE_UNPAYMENT -> {
            }
            OrderObservable.ORDERTYPE_SUBMIT ->
                // typeInfo = "已提交订单";
                index = 0
            OrderObservable.ORDERTYPE_RECEIVEORDER ->
                // typeInfo = "商家接单";
                index = 1
            OrderObservable.ORDERTYPE_DISTRIBUTION,
            OrderObservable.ORDERTYPE_DISTRIBUTION_RIDER_GIVE_MEAL,
            OrderObservable.ORDERTYPE_DISTRIBUTION_RIDER_TAKE_MEAL,
            OrderObservable.ORDERTYPE_DISTRIBUTION_RIDER_RECEIVE ->
                // typeInfo = "配送中";
                index = 2
            OrderObservable.ORDERTYPE_SERVED ->
                // typeInfo = "已送达";
                index = 3
            OrderObservable.ORDERTYPE_CANCELLEDORDER -> {
            }
        }// typeInfo = "未支付";
        // typeInfo = "取消的订单";
        return index
    }

    override fun update(o: Observable?, data: Any?) {
        // 观察者的响应
        val jsonObject = JSONObject(data as String)
        val pushOrderId = jsonObject.getString("orderId")
        val pushOrderType = jsonObject.getString("type")
        if (orderId == pushOrderId) {
            type = pushOrderType
        }
        setState()

        when (type) {
            OrderObservable.ORDERTYPE_RECEIVEORDER -> {
                //显示地图
                mMapView.visibility = View.VISIBLE
                // 移动地图
                aMap.moveCamera(
                    CameraUpdateFactory.newLatLngZoom(
                        LatLng(35.434534, 116.631722),
                        16f
                    )
                )
                // 标注卖家
                val sellerMarker = aMap.addMarker(
                    MarkerOptions()
                        .position(LatLng(35.434534, 116.631722))
                        .title("脆皮炸鸡")
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.order_seller_icon))
                        .snippet("我是卖家")
                )

                // 买家
                val imageView = ImageView(this)
                imageView.setImageResource(R.drawable.order_buyer_icon)
                val buyerMarker = aMap.addMarker(
                    MarkerOptions()
                        .position(LatLng(35.44671, 116.633374))
                        .title("名苑小区")
                        .icon(BitmapDescriptorFactory.fromView(imageView))
                        .snippet("我是买家")
                )
            }
            OrderObservable.ORDERTYPE_DISTRIBUTION -> {
                points.add(LatLng(35.434106, 116.632816))
                // 骑士登场
                val imageView = ImageView(this)
                imageView.setImageResource(R.drawable.order_rider_icon)
                riderMarker = aMap.addMarker(
                    MarkerOptions()
                        .position(LatLng(35.434106, 116.632816))
                        .title("外卖骑士")
                        .icon(BitmapDescriptorFactory.fromView(imageView))
                        .snippet("外卖小哥")
                )
            }
            OrderObservable.ORDERTYPE_DISTRIBUTION_RIDER_GIVE_MEAL,
            OrderObservable.ORDERTYPE_DISTRIBUTION_RIDER_TAKE_MEAL -> {

                if (jsonObject.has("lat")) {
                    val lat = jsonObject.getString("lat")
                    val lng = jsonObject.getString("lng")

                    // 更新骑士位置就是用新位置重新标记骑手
                    riderMarker.hideInfoWindow()
                    riderMarker.position = LatLng(lat.toDouble(), lng.toDouble())
                    aMap.moveCamera(
                        CameraUpdateFactory.newLatLngZoom(
                            LatLng(lat.toDouble(), lng.toDouble()),
                            16f
                        )
                    )
                    // 测距功能  参数1外卖员经纬度   参数2买家经纬度
                    val distance = AMapUtils.calculateLineDistance(
                        LatLng(lat.toDouble(), lng.toDouble()),
                        LatLng(35.433387, 116.633303)
                    )
                    riderMarker.title = "距离您还有" + abs(distance) + "米"
                    riderMarker.showInfoWindow()

                    // 绘制轨迹
                    points.add(LatLng(lat.toDouble(), lng.toDouble()))
                    val polyline = aMap.addPolyline(
                        PolylineOptions()
                            .width(10f)
                            .color(Color.argb(255, 1, 1, 1))
                            .add(
                                points[points.size - 1],
                                points[points.size - 2]
                            )
                    )
                }

            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy()
    }

    override fun onResume() {
        super.onResume()
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState)
    }
}